﻿using System;
using Unity;

namespace Container.Library
{
    public class UnityCIContainer
    {
        private readonly IUnityContainer container;
        private static readonly UnityCIContainer instance = new UnityCIContainer();

        private static object _sync = new object();

        private UnityCIContainer()
        {
            //注入配置对象
            container = new UnityContainer();
            var registerDics = RegisterTypeManager.GetTypesList();
            if (registerDics.Count>0)
            {
                foreach (var item in registerDics)
                {
                    container.RegisterType(
                        ReflectionHelper.GetType(item.Value.InterfaceOrNamespace.Split(',')[0], item.Value.InterfaceOrNamespace.Split(',')[1]),
                        ReflectionHelper.GetType(item.Value.ImplementOrProfile.Split(',')[0], item.Value.ImplementOrProfile.Split(',')[1])
                   );
                }
            }
        }

        /// <summary>
        /// 单例
        /// </summary>
        public static UnityCIContainer Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (_sync)
                    {
                        //如果类的实例不存在则创建，否则直接返回
                        if (instance == null)
                            return new UnityCIContainer();
                    }
                }
                return instance;
            }

        }

        /// <summary>
        /// 获取注入容器
        /// </summary>
        public object GetService(Type serviceType)
        {
            return container.Resolve(serviceType);
        }


        /// <summary>
        /// 获取注入容器
        /// </summary>
        public T GetService<T>()
        {
            return container.Resolve<T>();
        }
    }
}
